<html>
<head>
  <title>Chat via WebSocket</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
  <script type="text/javascript">

    // I adapted this code from a Jetty Server example.
    if (!window.WebSocket)
        alert("WebSocket not supported by this browser");

    // Get an Element
    function $() { return document.getElementById(arguments[0]); }
    // Get the value of an Element
    function $F() { return document.getElementById(arguments[0]).value; }

    var client = {
       connect: function(){
         this._ws=new WebSocket("ws://"+window.location["host"]+"/chat");
         this._ws.onopen=this._onopen;
         this._ws.onmessage=this._onmessage;
         this._ws.onclose=this._onclose;
       },

       _onopen: function(){
          $('connect').className='hidden';
          $('connected').className='';
          $('phrase').focus();
       },

       _send: function(message){
           if (this._ws)
            this._ws.send(message);
        },

       chat: function(text) {
          if (text != null && text.length>0 )
            client._send(text);
        },

        _onmessage: function(m) {
          if (m.data){
            var text = m.data;
            jQuery("#msgs").prepend("<span>" + text + "</br></span>");
          }
        },

        _onclose: function(m) {
          this._ws=null;
          $('connect').className='';
          $('connected').className='hidden';
          $('msg').innerHTML='';
        }

    };
  </script>
  <style type='text/css'>
    div.hidden { display: none; }
  </style>

</head>
<body>
  <h1>Chat via WebSocket</h1>
  <div id="connect">
     <input id='cA' class='button' type='submit' name='connect' value='Connect'/>
  </div>
  <br/>
  <div id="connected" class="hidden">
    Your Name:&nbsp;<input id='name' type='text'/></br>
    Say Something:&nbsp;<input id='phrase' type='text'/>
    <input id='sendB' class='button' type='submit' name='connect' value='Send'/>
  </div>
  <div id="msgs"></div>

  <script type='text/javascript'>
    $('cA').onclick = function(event) { client.connect(); return false; };
    $('sendB').onclick = function(event) {
      client.chat($F('name') + ": " + $F('phrase'));
      $('phrase').value = '';
      $('phrase').focus();
      return false;
    };
 </script>
  </body>
</html>

